package com.sunlee.app.api.resolver;

import com.sunlee.common.core.enums.ErrorCodeEnum;
import com.sunlee.common.core.exception.BusinessException;
import com.sunlee.common.service.entity.CommonUserEntity;
import com.sunlee.common.service.enums.StatusEnum;
import com.sunlee.app.api.annotation.LoginUser;
import com.sunlee.app.api.interceptor.AuthorizationInterceptor;
import com.sunlee.app.api.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 有@LoginUser注解的方法参数，注入当前登录用户
 * 已废弃，使用UserContext获取用户信息
 *
 * @author sunlee
 */
@Deprecated
@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private UserService userService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(CommonUserEntity.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) {
        //获取用户ID
        Object object = request.getAttribute(AuthorizationInterceptor.USER_KEY, RequestAttributes.SCOPE_REQUEST);
        if (object == null) {
            return null;
        }

        //获取用户信息
        CommonUserEntity userInfo = userService.getUserByUserId((Long) object);

        // 黑名单账号
        if(StatusEnum.INVALID.getCode() == userInfo.getStatus()){
            throw new BusinessException(ErrorCodeEnum.USER_ACCOUNT_DISABLED);
        }

        return userInfo;
    }
}
